package org.zsk.cs.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.zsk.cs.common.exception.impl.ResultCommonEnum;
import org.zsk.cs.exception.BizException;
import org.zsk.cs.response.ResultBody;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *     全局异常处理
 * </p>
 *
 * @author zsk
 * @version 1.0
 * Created on 2020/3/30
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ResultBody bizExceptionHandler(HttpServletRequest req, BizException e){
        log.error("发生业务异常！原因是：{}",e.getErrorMsg());
        return ResultBody.error(e.getErrorCode(),e.getErrorMsg());
    }

    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public ResultBody exceptionHandler(HttpServletRequest req, NullPointerException e){
        log.error("发生空指针异常！原因是:",e);
        return ResultBody.error(ResultCommonEnum.BODY_NOT_MATCH);
    }

    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =IllegalArgumentException.class)
    @ResponseBody
    public ResultBody exceptionHandler(HttpServletRequest req, IllegalArgumentException e){
        log.error("非法参数！原因是:",e);
        return ResultBody.error(ResultCommonEnum.BODY_NOT_MATCH);
    }

    /**
     * 处理邮件的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = MessagingException.class)
    @ResponseBody
    public ResultBody exceptionHandler(HttpServletRequest req, MessagingException e){
        log.error("邮件发送失败:",e);
        return ResultBody.error(ResultCommonEnum.SERVER_BUSY);
    }

    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public ResultBody exceptionHandler(HttpServletRequest req, Exception e){
        log.error("未知异常！原因是:",e);
        return ResultBody.error(ResultCommonEnum.INTERNAL_SERVER_ERROR);
    }
}
